import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
// import { loadDataAsync, decrementInventory } from './actionCreator'
import * as prodActions from './actionCreator'
import { actionCreator as cartActions } from '../cart'

import ProductsUi from './ProductsUi'

@connect(
  state => ({
    products: state.product.all
  }),

  // dispatch => ({
  //   loadData() {
  //     dispatch(loadDataAsync())
  //   },

  //   addToCart(product) {
  //     // 调用另外一个功能模块的reducer，添加产品到购物车
  //     dispatch(cartActions.addToCart(product))
  //     // 调用产品模块的reducer， 减少库存
  //     dispatch(decrementInventory(product))
  //     // 求一次总价
  //     dispatch(cartActions.culprice())
  //   }
  // })
)
export default class Products extends Component {
  constructor(props) {
    super(props)
    this.actions = bindActionCreators(
      {
        ...prodActions,
        ...cartActions
      }, 
      this.props.dispatch
    )
  }

  addToCart = (product) => {
    this.actions.addToCart(product)
    this.actions.decrementInventory(product)
    this.actions.culprice()
  }

  async componentDidMount() {
    // 直接调用通过bindActionCreator绑定过的actions
    this.actions.loadDataAsync()
    // this.props.loadData()
  }

  render() {
    return (
      <ProductsUi 
        products={this.props.products}
        addToCart={this.addToCart}
      ></ProductsUi>
    )
  }
}
